package com.weibei.common.utils.jd;

import com.weibei.common.utils.security.Sha256;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class JdUtil {
    private static final Logger logger = LoggerFactory.getLogger(JdUtil.class);

    public static String sha256Str(Object bean) throws Exception {
        return Sha256.getSHA256(JdUtil.sortParam(JdUtil.bean2map(bean)));
    }

    /**
     * javabean转换为map
     * @param bean
     * @return
     * @throws Exception
     */
    public static Map<String,Object> bean2map(Object bean) {
        Map<String,Object> map = new HashMap<>();
        try {
            BeanInfo info = Introspector.getBeanInfo(bean.getClass(),Object.class);
            PropertyDescriptor[]pds=info.getPropertyDescriptors();
            for(PropertyDescriptor pd:pds) {
                String key = pd.getName();
                Object value=  pd.getReadMethod().invoke(bean);
                map.put(key, value);
            }
        } catch (Exception e) {
            logger.error("bean2map error" + bean.toString(), e);
        }
        return map;
    }

    /**
     * 将集合M内非空参数值的参数按照参数名ASCII码从小到大排序（字典序），
     * 使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串stringA
     * @param reMap
     * @return
     */
    public static String sortParam(Map<String, Object> reMap) {
        StringBuilder sb = new StringBuilder();
        if (!org.springframework.util.StringUtils.isEmpty(reMap)) {
            TreeMap<String, Object> treeMap = new TreeMap<>();
            treeMap.putAll(reMap);
            Set<String> keys = treeMap.keySet();
            for (String key : keys) {
                if (org.springframework.util.StringUtils.isEmpty(treeMap.get(key))) {
                    continue;
                }
                if ("sign".equals(key) || "version".equals(key)) {
                    continue;
                }
                sb.append(key + "=" + treeMap.get(key) + "&");
            }
        }
        String fullStr = sb.toString();
        if(fullStr.endsWith("&")){
            fullStr = fullStr.substring(0,fullStr.length() -1);
        }
        return fullStr;
    }

}
